package com.esdemo.controller;

import com.alibaba.fastjson.JSON;
import com.esdemo.entity.Shopping;
import com.esdemo.repository.ShoppingRepository;
import com.esdemo.service.ShoppingService;
import com.esdemo.service.ShoppingUserService;
import com.esdemo.utils.CommonResult;
import com.esdemo.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.util.DigestUtils;


import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "search")
public class ShoppingController {

    @Autowired
    private ShoppingService shoppingService;

    @Autowired
    private ShoppingRepository shoppingRepository;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private ShoppingUserService shoppingUserService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    //Es添加数据
    @RequestMapping("/add")
    @ResponseBody
    public Object addShopping(){
        List<Shopping> shoppingList=shoppingService.findShoppingList(0,100);
        Iterable saveAll=null;
        if (shoppingList != null && shoppingList.size()!=0){
            saveAll=shoppingRepository.saveAll(shoppingList);
        }
        return JSON.toJSONString(saveAll);
    }
    //根据描述聚合查询
    @RequestMapping("/getShopDesc")
    @ResponseBody
    public Map<String,Object> findShoppingByShopDesc(String desc){
        return shoppingService.getShoppingByShopDesc(desc);
    }


    //登录生成token
    @RequestMapping("/login")
    @ResponseBody
    public CommonResult login(String username, String password){
        String token=shoppingUserService.login(username,DigestUtils.md5DigestAsHex(password.getBytes()));
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        return CommonResult.success(tokenMap);
    }

    //从token中获取JWT中的负载
    @RequestMapping("/jx")
    @ResponseBody
    public CommonResult jx(String token){
        Claims claims=jwtTokenUtil.getClaimsFromToken(token);
        Map<Object, Object> tokenMap = new HashMap<>();
        tokenMap.put("claims", claims);
        return CommonResult.success(tokenMap);
    }
}
